package com.test.springCloud.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import org.springframework.stereotype.Component;

@Component
public class JwtUtil {
	/**
	 * 过期5分钟
	 */
	public static final int EXPIRE_TIME = 1000 * 60 * 60 * 24 * 7;

	/**
	 * jwt密钥
	 */
	private static final String SECRET = "jwt_secret";

	/**
	 * token私钥，不可以暴露
	 */

	/**
	 * 生成jwt字符串，五分钟后过期 JWT(json web token)
	 * 
	 * @param userId
	 * @param info,Map的value只能存放值的类型为：Map，List，Boolean，Integer，Long，Double，String and
	 *                                                                            Date
	 * @return
	 */
	public static String sign(String userId, Map<String, Object> info) {
		try {
			Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
			Algorithm algorithm = Algorithm.HMAC256(SECRET);
			return JWT.create()
					// 将userId保存到token里面
					.withAudience(userId)
					// 存放自定义数据
					.withClaim("info", info)
					// 五分钟后token过期
					.withExpiresAt(date)
					// token的密钥
					.sign(algorithm);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 根据token获取userId
	 * 
	 * @param token
	 * @return
	 */
	public static String getUserId(String token) {
		try {
			String userId = JWT.decode(token).getAudience().get(0);
			return userId;
		} catch (JWTDecodeException e) {
			return null;
		}
	}

	public static String getClaim(String token) {
		try {
			Algorithm algorithm = Algorithm.HMAC256(SECRET);
			DecodedJWT decodedJWT = JWT.require(algorithm).build().verify(token);
			Claim claim = decodedJWT.getClaim("userName");
			return claim.asString();
		} catch (JWTDecodeException e) {
			return null;
		}
	}

	/**
	 * 根据token获取自定义数据info
	 * 
	 * @param token
	 * @return
	 */
	public static Map<String, Object> getInfo(String token) {
		try {
			return JWT.decode(token).getClaim("info").asMap();
		} catch (JWTDecodeException e) {
			return null;
		}
	}

	/**
	 * 校验token 通过返回过期时间
	 * 
	 * @param token
	 * @return
	 */
	public static String checkSign(String token) {
		try {
			Algorithm algorithm = Algorithm.HMAC256(SECRET);
			DecodedJWT verifier = JWT.require(algorithm).build().verify(token);
			String expires = DateUtil.format(verifier.getExpiresAt(), "yyyy-MM-dd HH:mm:ss");
			return expires;
		} catch (JWTVerificationException e) {
			return null;
		}
	}

	/**
	 * 创建token
	 *
	 * @param userId  用户ID
	 * @param userName 用户名
	 * @return token
	 */
	public static String createToken(Integer userId, String userName) {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, 3);
		System.out.println(calendar.getTime());
		return JWT.create()
				// 签发对象
				.withAudience(userId + "")
				// 唯一表示
				.withJWTId(UUID.randomUUID(true).toString())
				// 载荷
				.withClaim("userName", userName)
				// 签发时间
				.withIssuedAt(new Date())
				// 有效时间
				.withExpiresAt(calendar.getTime())
				// 加密
				.sign(Algorithm.HMAC256(SECRET));
	}

}